package com.polaris.live.manager

import com.google.firebase.messaging.FirebaseMessaging
import com.polaris.live.common.AppModule
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.manager.withRetryNow
import com.polaris.live.net.userService
import com.polaris.live.resp.go_resp.FcmNoticeTokenBean
import kotlinx.coroutines.launch

/**
 * PushManager
 *
 * @author Created by lucas on 2023/12/15 07:11
 */
object GooglePushManager {

    private var fcmToken: String? = null

    fun setFcmToken(token: String?) {
        fcmToken = token
    }

    fun login() {
        CoroutineScopeManager.ioScope.launch {
            try {
                if (!AppModule.checkGoogleServices()) return@launch
                val fcmToken = fcmToken
                if (fcmToken == null) {
                    FirebaseMessaging.getInstance().token.addOnCompleteListener {
                        if (it.isSuccessful) {
                            GooglePushManager.fcmToken = it.result

                            CoroutineScopeManager.ioScope.launch {
                                uploadToken(it.result)
                            }
                        }
                    }
                } else {
                    uploadToken(fcmToken)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private suspend fun uploadToken(fcmToken: String) {
        withRetryNow {
            userService.fcmNoticeToken(FcmNoticeTokenBean(fcmToken))
        }
    }
}